package test

import (
	"gin-demo/common"
	"gin-demo/container"
	"gin-demo/entity"
	"gin-demo/service/test"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func AddTestRouter(engine *gin.Engine) {

	group := engine.Group("test")
	{
		group.GET("/list", testList)
		group.POST("/", testCreate)
	}
}

// @Summary test接口
// @Description 创建test
// @Tags test
// @Accept application/json
// @Produce application/json
// @Success 200 {object} common.Response
// @Failure 400 {object} common.Response
// @Failure 500 {object} common.Response
// @Router /test/ [post]
func testCreate(context *gin.Context) {

	service := container.Get("testService").(test.TestServiceImp)

	var t entity.Test
	err := context.ShouldBind(&t)
	t.UpdateTime = time.Now().Unix()
	if err != nil {
		return
	}
	create, err := service.Create(&t)
	response := common.NewCommonResponse()
	if err != nil {
		response.Code = common.CodeTestCreateFail
		response.Message = common.MsgTestCreateFail
	}
	response.Data = create
	context.JSON(response.Code, response)
}

// @Summary test接口
// @Description 获取test列表
// @Tags test
// @Accept application/json
// @Produce application/json
// @Success 200 {object} common.Response
// @Failure 400 {object} common.Response
// @Failure 500 {object} common.Response
// @Router /test/list [get]
func testList(context *gin.Context) {
	pageNum, _ := strconv.Atoi(context.Query("pageNum"))
	pageSize, _ := strconv.Atoi(context.Query("pageSize"))

	var pageRequest common.PageRequest
	pageRequest.PageNum = pageNum
	pageRequest.PageSize = pageSize
	service := container.Get("testService").(test.TestServiceImp)

	list, err := service.List(pageRequest)
	response := common.NewCommonResponse()
	if err != nil {
		response.Code = common.CodeTestListFail
		response.Message = common.MsgTestListFail
	}

	response.Data = list

	context.JSON(response.Code, response)

}
